﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Ex04.Menus.Delegates
{
    public class SubMenu : IMenuItem
    {
        private string m_DisplayText;
        private string m_BackText;
        private List<IMenuItem> m_MenuItemCollection;

        public SubMenu(string i_DisplayText)
        {
            m_BackText = "Back";
            m_DisplayText = i_DisplayText;
            m_MenuItemCollection = new List<IMenuItem>();
        }

        public SubMenu(string i_DisplayText, string i_BackText)
            : this(i_DisplayText)
        {
            m_BackText = i_BackText;
        }

        public string DisplayText
        {
            get { return m_DisplayText; }
        }

        /// <summary>
        /// Selects the item.
        /// </summary>
        public void Select()
        {
            int userChoice;

            do
            {
                Console.Clear();
                showTitleAndMenuItems();
                userChoice = getUserChoice();

                if (userChoice != 0)
                {
                    m_MenuItemCollection[userChoice - 1].Select();
                }
            }
            while (userChoice != 0);
        }

        private void showTitleAndMenuItems()
        {
            string line;
            Console.WriteLine(m_DisplayText);

            for (int i = 0; i < m_MenuItemCollection.Count; i++)
            {
                IMenuItem currentMenuItem = m_MenuItemCollection[i];
                line = string.Format("{0}. {1}", (i + 1).ToString(), currentMenuItem.DisplayText);
                Console.WriteLine(line);
            }
            
            line = string.Format("{0}. {1}{2}", 0, m_BackText, Environment.NewLine);
            Console.WriteLine(line);
        }

        private int getUserChoice()
        {
            int userChoice;
            string messageToUser = string.Format("Please enter your choice and then press Enter. (A number between {0} and {1}.)", 0, m_MenuItemCollection.Count);
            Console.WriteLine(messageToUser);
            string userChoiceString = Console.ReadLine();
            bool parsingSuccess = int.TryParse(userChoiceString, out userChoice);
            if (!parsingSuccess || userChoice < 0 || userChoice > m_MenuItemCollection.Count)
            {
                userChoice = getUserChoice();
            }

            return userChoice;
        }

        /// <summary>
        /// Adds a menu item to the main menu.
        /// </summary>
        /// <param name="i_MenuItem">The menu item to add.</param>
        public void AddMenuItem(IMenuItem i_MenuItem)
        {
            m_MenuItemCollection.Add(i_MenuItem);
        }
    }
}